package client;

import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.Queue;

import communication.ClientComm;
import communication.ComandoComm;
import communication.ServerComm;

public class ClientCommLocale implements ClientComm, Runnable {
	private Thread listener; 
	private ServerComm server;
	private ClientModel client;
	private Queue<String> codaFromServer;
	private boolean exiting;
	
	public ClientCommLocale(ServerComm server, ClientModel client){
		this.server = server;
		this.client = client;
		exiting = false;
		codaFromServer = new LinkedList<String>();
		listener = new Thread(this, "clientCommLocale");
		listener.start();
	}
	@Override
	public synchronized void run(){
		while(!exiting){
			while (!codaFromServer.isEmpty()) {
				boolean sent = false;
				while(!sent)
					sent = client.arrivaMsgFromServer(codaFromServer.poll());
			}
			try {
				wait();
			} catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		try {
		server.close();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	//override field server when a direct servercommlocale is ready
	public void setConnection(ServerComm srv){
		this.server = srv;
	}
	@Override
	public synchronized void msgFromServer(String msg){
		codaFromServer.offer(msg);
		notify();
	}
	@Override
	public void sendRequest(String msg){
		try {
		if (msg.contains(ComandoComm.login.toString()) || msg.contains(ComandoComm.creaUtente.toString())){
			server.connect(this);
		}
		server.msgFromClient(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
			sendRequest(msg);
		}
	}
	@Override
	public void clearMessages() {
		codaFromServer.clear();
	}
	@Override
	public synchronized void close() {
		exiting = true;
		notify();
	}
}
